#!/usr/bin/env python3
"""
使用在线Mermaid服务生成PNG图片
"""

import requests
import base64
import json
from pathlib import Path


def mermaid_to_png(mermaid_code: str, output_path: str = "travel_agent_workflow.png"):
    """
    使用在线Mermaid服务将代码转换为PNG图片
    
    Args:
        mermaid_code: Mermaid代码
        output_path: 输出PNG文件路径
    """
    try:
        # 编码Mermaid代码
        encoded = base64.b64encode(mermaid_code.encode('utf-8')).decode('ascii')
        
        # 构建Mermaid.ink URL
        url = f"https://mermaid.ink/img/{encoded}"
        
        print(f"正在从 {url} 下载图片...")
        
        # 下载图片
        response = requests.get(url, timeout=30)
        response.raise_for_status()
        
        # 保存图片
        with open(output_path, 'wb') as f:
            f.write(response.content)
        
        print(f"✓ PNG图片已生成: {output_path}")
        print(f"图片大小: {len(response.content)} bytes")
        
        return True
        
    except Exception as e:
        print(f"生成PNG图片失败: {e}")
        return False


def main():
    """主函数"""
    print("=== LangGraph工作流PNG图片生成器 ===")
    
    # 读取Mermaid代码
    mermaid_file = "travel_agent_workflow.mmd"
    if not Path(mermaid_file).exists():
        print(f"错误: 找不到Mermaid文件 {mermaid_file}")
        print("请先运行 generate_workflow_diagram.py 生成Mermaid代码")
        return
    
    with open(mermaid_file, 'r', encoding='utf-8') as f:
        mermaid_code = f.read()
    
    print(f"已读取Mermaid代码: {len(mermaid_code)} 字符")
    
    # 生成PNG图片
    success = mermaid_to_png(mermaid_code, "travel_agent_workflow.png")
    
    if success:
        print("\n✓ 工作流PNG图片生成成功!")
        print("您可以使用以下方式查看图片:")
        print("1. 直接在文件管理器中打开 travel_agent_workflow.png")
        print("2. 在支持Mermaid的Markdown编辑器中查看 travel_agent_workflow.mmd")
        print("3. 在线Mermaid编辑器: https://mermaid.live/")
    else:
        print("\n✗ 工作流PNG图片生成失败")
        print("您可以:")
        print("1. 手动将 travel_agent_workflow.mmd 内容复制到 https://mermaid.live/")
        print("2. 使用支持Mermaid的编辑器查看 .mmd 文件")


if __name__ == "__main__":
    main()
